<template>
  <el-form 
    :model="formData" 
    ref="formRef" 
    label-width="120px"
    class="demo-form"
  >
    <el-form-item 
      v-for="(field, index) in config.fields" 
      :key="index"
      :label="field.label"
      :prop="field.name"
      :rules="getFormRules(field.rules)"
    >
      <el-input 
        v-if="field.type === 'input'"
        v-model="formData[field.name]"
        :placeholder="field.placeholder"
      />
      
      <el-select 
        v-if="field.type === 'select'"
        v-model="formData[field.name]"
        :placeholder="field.placeholder || '请选择'"
      >
        <el-option 
          v-for="option in field.options"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      
      <el-date-picker 
        v-if="field.type === 'date'"
        v-model="formData[field.name]"
        type="date"
        placeholder="选择日期"
      />
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">
        {{ config.submit_text || '提交' }}
      </el-button>
      <el-button @click="handleReset">
        {{ config.reset_text || '重置' }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const props = defineProps({
  config: {
    type: Object,
    required: true
  }
})

const formRef = ref(null)
const formData = reactive({})

onMounted(() => {
  props.config.fields.forEach(field => {
    formData[field.name] = ''
  })
})

const getFormRules = (ruleKeys = []) => {
  const ruleMap = {
    required: { required: true, message: '该字段为必填项', trigger: 'blur' },
    'minLength:3': { min: 3, message: '长度不能少于3个字符', trigger: 'blur' },
    phone: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    email: { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  }
  return ruleKeys.map(key => ruleMap[key])
}

const handleSubmit = () => {
  formRef.value.validate().then(() => {
    alert('表单提交成功，数据：' + JSON.stringify(formData))
  }).catch(err => {
    console.error('表单校验失败：', err)
  })
}

const handleReset = () => {
  formRef.value.resetFields()
}
</script>

<style scoped>
.demo-form {
  max-width: 600px;
}
</style>